package com.xiaodou.mjf.infrastructure.common.utils;

import java.io.File;
import java.io.InputStream;
import java.util.Calendar;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Rocky on 14/12/21.
 */
public class FileUtils extends org.apache.commons.io.FileUtils{

    static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    public static boolean exists(String path){
        File file = new File(path);
        if(file.exists()){
            return true;
        }
        return false;
    }

    public static void mkdirs(String path){
        File file = new File(path);
        file.mkdirs();
    }

    /*
    public static String getPath(String type,String fileName){
        String baseDir = Global.getConsoleBaseDir();

        Calendar cal = Calendar.getInstance();

        StringBuffer sb = new StringBuffer();
        sb.append(baseDir);
        sb.append("/");
        sb.append(type);
        sb.append("/");
        sb.append(cal.get(Calendar.YEAR));
        sb.append("/");
        sb.append(cal.get(Calendar.MONTH));
        sb.append("/");
        sb.append(cal.get(Calendar.DATE));
        sb.append("/");
        sb.append(CodeGenerator.UUID());
        sb.append(FilenameUtils.EXTENSION_SEPARATOR_STR);
        sb.append(FilenameUtils.getExtension(fileName));

        return sb.toString();
    }
    
    */

    public static String getPath(String type){

        String baseDir = Global.getConsoleBaseDir();

        Calendar cal = Calendar.getInstance();

        StringBuffer sb = new StringBuffer();
        sb.append(baseDir);
        sb.append("/");
        sb.append(type);
        sb.append("/");
        sb.append(cal.get(Calendar.YEAR));
        sb.append("/");
        sb.append(cal.get(Calendar.MONTH) + 1);
        sb.append("/");
        sb.append(cal.get(Calendar.DATE));

        return sb.toString();
    }
    
    public static String getPath(String type,String entityId){

        String baseDir = Global.getConsoleBaseDir();

        Calendar cal = Calendar.getInstance();

        StringBuffer sb = new StringBuffer();
        sb.append(baseDir);
        sb.append("/");
        sb.append(type);
        sb.append("/");
        sb.append(cal.get(Calendar.YEAR));
        sb.append("/");
        sb.append(cal.get(Calendar.MONTH) + 1);
        sb.append("/");
        sb.append(cal.get(Calendar.DATE));
        sb.append("/");
        sb.append(entityId);

        return sb.toString();
    }

    public static String getFileName(String fileName){

    	StringBuffer sb = new StringBuffer();
    	sb.append(CodeGenerator.UUID());
        sb.append(FilenameUtils.EXTENSION_SEPARATOR_STR);
        sb.append(FilenameUtils.getExtension(fileName));

        return sb.toString();

    }

    public static boolean upload(InputStream inputStream,File file){

        if(file.exists()){
            file.mkdirs();
        }

        try {
            copyInputStreamToFile(inputStream, file);
            return true;
        }catch(Exception e){
            logger.error("文件上传失败:{}",e.getMessage());
            return false;
        }

    }

    /**
     * 上传文件到FTPServer
     * @param host
     * @param user
     * @param password
     * @param port
     * @param inputStream
     * @param path
     * @param fileName
     * @return
     */
    public static boolean upload(String host,String user,String password,Integer port,InputStream inputStream,String path,String fileName){
    	
    	FTPClient client = new FTPClient();
    	try{
    		int reply = -1;
    		client.connect(host, port);
    		client.login(user, password);
    		reply = client.getReplyCode();
    		if(!FTPReply.isPositiveCompletion(reply)){
    			client.disconnect();
    			return false;
    		}

    		createFtpDirectory(client, path);

    		client.setFileType(FTP.BINARY_FILE_TYPE);
    		client.storeFile(fileName, inputStream);

    		inputStream.close();
    		client.logout();
    		return true;

    	}catch(Exception e){
    		e.printStackTrace();
    	}

    	return false;
    }

    private static void createFtpDirectory(FTPClient client,String path) throws Exception{
    	String[] pathnames = StringUtils.split(path,"/");
    	for(String name:pathnames){
    		client.makeDirectory(name);
    		client.changeWorkingDirectory(name);
    	}
    }
    
    /**
     * 删除单个文件
     * @param path 文件路径
     * @return
     */
    public static boolean deleteFile(String path){
        File file = new File(path);
        if(file.exists() && file.isFile()){
            if(file.delete()){
                logger.debug("删除单个文件{}成功",path);
                return true;
            }else{
                logger.debug("删除单个文件{}失败",path);
                return false;
            }
        }
        return false;
    }

    /**
     * 创建单个文件
     * @param path
     * @return
     */
    public static boolean createFile(String path){
        File file = new File(path);
        if(file.exists()){
            logger.debug("文件{}已存在",path);
            return false;
        }
        if(path.endsWith(File.separator)){
            logger.debug("{}为目录，无法创建目录",path);
            return false;
        }
        if(!file.getParentFile().exists()){
            if(!file.getParentFile().mkdirs()){
                logger.debug("创建{}上级目录失败",path);
                return false;
            }
        }

        try{
            if(file.createNewFile()){
                logger.debug("{}文件创建成功",path);
                return true;
            }else{
                logger.debug("{}文件创建失败",path);
                return false;
            }
        }catch (Exception e){
            logger.debug("文件{}创建失败:{}",path,e.getMessage());
            return false;
        }


    }

    public static void main(String[] args) {
		//FileUtils.createFtpDirectory(StringUtils.split("/userfiles/console/link/2015/0/4","/"), );
	}
}
